#include <cstdio>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <esp_log.h>
#include <my_wifi.h>
#include <auto_json.h>
#include <my_webserver.h>
#include <my_spiffs.h>
#include <map>
#include <driver/uart.h>
#include <hal/uart_ll.h>
#include <driver/gpio.h>
#include <my_wifi.h>

constexpr const char *TAG = "Application";
constexpr const uart_port_t UART_NUM = UART_NUM_1;
constexpr const size_t UART_BUFFER_SIZE = 1024 * 2;
constexpr const gpio_num_t UART_TX_PIN = GPIO_NUM_16;
constexpr const gpio_num_t UART_RX_PIN = GPIO_NUM_17;

WiFi wifi("ESP32", "");

extern "C" void app_main(void)
{
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    SPIFFS.begin();

    uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_DEFAULT,
    };

    uart_param_config(UART_NUM, &uart_config);
    uart_driver_install(UART_NUM, UART_BUFFER_SIZE, UART_BUFFER_SIZE / 2, 0, NULL, 0);

    uart_set_pin(UART_NUM, UART_TX_PIN, UART_RX_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);

    while (1)
    {
        vTaskDelay(500 / portTICK_PERIOD_MS);
        uart_write_bytes(UART_NUM, "hello world\n", strlen("hello world\n"));
    }
}